// 添加新的模块
pub mod aria;
#[cfg(test)]
mod aria_tests;
pub mod encoding; // 新增编码与国际化模块
pub mod form;
pub mod mathml;
mod selector;
pub mod svg;
#[cfg(test)]
mod tests;
mod validator;

// 修复导入路径
use html5ever::interface::tree_builder::TreeSink;
use html5ever::interface::QualName;
// 添加缺失的namespace_url宏导入
use html5ever::namespace_url;
use once_cell::sync::Lazy;
use std::borrow::Cow;
use std::cell::{Ref, RefCell};
use std::collections::HashMap;
use std::default::Default;
use std::ops::Deref;
use std::rc::Rc;
use std::str::FromStr;
use std::sync::Arc;
use string_cache::Atom;

// 添加ego_tree导入
use ego_tree::NodeRef;

pub use aria::{AriaAttributeType, AriaManager, AriaRoleCategory};
pub use encoding::{EncodingDetector, Internationalization, TextDirection};
pub use selector::{AttributeOperator, Selector, SelectorParseError};
pub use validator::{HtmlValidator, ValidationError};

use html5ever::tendril::{StrTendril, TendrilSink};
use html5ever::tree_builder::{ElementFlags, NodeOrText, QuirksMode};
use html5ever::{ns, LocalName, Namespace};

// 使用scraper替代html5ever::rcdom
use scraper::{element_ref::ElementRef, Html, Node};

thread_local! {
    static CURRENT_NAME: RefCell<String> = RefCell::new(String::new());
    static CURRENT_QNAME: RefCell<Box<QualName>> = RefCell::new(Box::new(QualName::new(
        None,
        ns!(html),
        LocalName::from("div")
    )));
}

// 使用静态QualName存储
static HTML_NS: Lazy<Namespace> = Lazy::new(|| ns!(html));
static DEFAULT_QNAME: Lazy<Box<QualName>> =
    Lazy::new(|| Box::new(QualName::new(None, HTML_NS.clone(), LocalName::from("div"))));

thread_local! {
    static ELEM_QNAME: RefCell<Box<QualName>> = RefCell::new(Box::new(QualName::new(
        None,
        HTML_NS.clone(),
        LocalName::from("")
    )));
}

/// HTML解析错误类型
#[derive(Debug)]
pub enum HtmlParserError {
    ParseError(String),
    InvalidNode(String),
}

impl std::error::Error for HtmlParserError {}

impl std::fmt::Display for HtmlParserError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HtmlParserError::ParseError(msg) => write!(f, "解析错误: {}", msg),
            HtmlParserError::InvalidNode(msg) => write!(f, "无效节点: {}", msg),
        }
    }
}

/// 解析器配置
#[derive(Debug, Clone)]
pub struct ParserConfig {
    /// 是否保留注释
    pub preserve_comments: bool,
    /// 是否执行自动修复
    pub auto_fix: bool,
    /// 文档编码（默认UTF-8）
    pub encoding: String,
    /// 是否保留空白文本节点
    pub preserve_whitespace: bool,
    /// 是否解码HTML实体
    pub decode_entities: bool,
    /// 是否启用国际化支持
    pub enable_i18n: bool,
}

impl Default for ParserConfig {
    fn default() -> Self {
        Self {
            preserve_comments: true,
            auto_fix: true,
            encoding: "UTF-8".to_string(),
            preserve_whitespace: false,
            decode_entities: true,
            enable_i18n: true,
        }
    }
}

/// HTML解析器结构体
#[derive(Debug)]
pub struct HtmlParser {
    config: ParserConfig,
    encoding_detector: EncodingDetector,
    i18n: Internationalization,
}

impl HtmlParser {
    /// 创建新的HTML解析器实例
    pub fn new(config: ParserConfig) -> Self {
        Self {
            encoding_detector: EncodingDetector::with_default_encoding(&config.encoding),
            i18n: Internationalization::new(),
            config,
        }
    }

    /// 解析HTML字符串
    pub fn parse(&self, html: &str) -> Result<DomNode, HtmlParserError> {
        // 检测编码
        let mut detector = self.encoding_detector.clone();
        detector.detect_from_meta(html);

        // 使用scraper库解析HTML
        let fragment = Html::parse_document(html);

        // 创建文档根节点
        let mut document = DomNode {
            node_type: NodeType::Document,
            attributes: vec![],
            children: vec![],
            parent: None,
            namespace: None,
        };

        // 遍历HTML并转换为DOM节点
        for child in fragment.tree.root().children() {
            if let Some(node) = self.convert_scraper_node(child) {
                document.children.push(node);
            }
        }

        Ok(document)
    }

    // 修改convert_scraper_node方法以处理命名空间
    fn convert_scraper_node(
        &self,
        node: ego_tree::NodeRef<'_, scraper::node::Node>,
    ) -> Option<DomNode> {
        match node.value() {
            scraper::node::Node::Element(element) => {
                let name = element.name().to_string();
                let mut dom_node;

                // 根据元素名称判断命名空间
                if svg::is_svg_element(&name) {
                    dom_node = svg::create_svg_element(&name);
                    svg::add_default_svg_attributes(&mut dom_node);
                } else if mathml::is_mathml_element(&name) {
                    dom_node = mathml::create_mathml_element(&name);
                    mathml::add_default_mathml_attributes(&mut dom_node);
                } else {
                    dom_node = DomNode::new_element(&name);
                }

                // 添加属性
                for (key, value) in element.attrs() {
                    // 检查xmlns属性以更新命名空间
                    if key == "xmlns" {
                        dom_node.namespace = Some(value.to_string());
                    }
                    dom_node.add_attribute(key, value);
                }

                // 处理子节点
                for child in node.children() {
                    if let Some(child_node) = self.convert_scraper_node(child) {
                        dom_node.children.push(child_node);
                    }
                }

                Some(dom_node)
            }
            scraper::node::Node::Text(text) => {
                let text_content = text.text.to_string();

                // 处理文本中的HTML实体
                let decoded_text = if self.config.decode_entities {
                    self.decode_html_entities(&text_content)
                } else {
                    text_content
                };

                if (!decoded_text.trim().is_empty() || self.config.preserve_whitespace) {
                    Some(DomNode::new_text(&decoded_text))
                } else {
                    None
                }
            }
            scraper::node::Node::Comment(comment) => {
                if self.config.preserve_comments {
                    Some(DomNode::new_comment(&comment.comment))
                } else {
                    None
                }
            }
            scraper::node::Node::Document => Some(DomNode {
                node_type: NodeType::Document,
                attributes: vec![],
                children: vec![],
                parent: None,
                namespace: None,
            }),
            scraper::node::Node::Doctype(doctype) => Some(DomNode {
                node_type: NodeType::DocumentType(doctype.name.to_string()),
                attributes: vec![],
                children: vec![],
                parent: None,
                namespace: None,
            }),
            // 处理其他节点类型
            _ => None,
        }
    }

    /// 解析HTML片段并添加到父节点
    fn parse_html_fragment(&self, html: &str, parent: &mut DomNode) -> Result<(), HtmlParserError> {
        // 简单的解析逻辑，递归创建标签和文本节点
        let mut chars = html.chars().peekable();
        let mut current_text = String::new();

        while let Some(c) = chars.next() {
            match c {
                '<' => {
                    // 处理标签开始
                    // 保存当前累积的文本
                    if !current_text.is_empty() {
                        if !current_text.trim().is_empty() || self.config.preserve_whitespace {
                            parent.children.push(DomNode::new_text(&current_text));
                        }
                        current_text.clear();
                    }

                    // 检查是否是注释
                    if chars.peek() == Some(&'!')
                        && chars.clone().nth(1) == Some('-')
                        && chars.clone().nth(2) == Some('-')
                    {
                        // 消费<!--
                        chars.next();
                        chars.next();
                        chars.next();

                        // 解析注释内容
                        let mut comment = String::new();
                        while let Some(c) = chars.next() {
                            if c == '-'
                                && chars.peek() == Some(&'-')
                                && chars.clone().nth(1) == Some('>')
                            {
                                chars.next();
                                chars.next(); // 消费-->
                                break;
                            }
                            comment.push(c);
                        }

                        if self.config.preserve_comments {
                            parent.children.push(DomNode::new_comment(&comment));
                        }
                        continue;
                    }

                    // 检查是否是闭合标签
                    let is_closing = chars.peek() == Some(&'/');
                    if is_closing {
                        chars.next(); // 消费/

                        // 解析标签名
                        let mut tag_name = String::new();
                        while let Some(c) = chars.next() {
                            if c == '>' {
                                break;
                            }
                            tag_name.push(c);
                        }

                        // 闭合标签只需要处理结束，不需要创建新节点
                        continue;
                    }

                    // 解析标签名和属性
                    let mut tag_name = String::new();
                    while let Some(&c) = chars.peek() {
                        if c.is_whitespace() || c == '>' || c == '/' {
                            break;
                        }
                        tag_name.push(chars.next().unwrap());
                    }

                    // 创建新元素节点
                    let mut element = DomNode::new_element(&tag_name);

                    // 解析属性
                    while let Some(&c) = chars.peek() {
                        if c == '>' || c == '/' {
                            break;
                        }

                        if c.is_whitespace() {
                            chars.next();
                            continue;
                        }

                        // 解析属性名
                        let mut attr_name = String::new();
                        while let Some(&c) = chars.peek() {
                            if c == '=' || c.is_whitespace() {
                                break;
                            }
                            attr_name.push(chars.next().unwrap());
                        }

                        // 消费等号和空白字符
                        while let Some(&c) = chars.peek() {
                            if c == '=' {
                                chars.next();
                                break;
                            }
                            if c.is_whitespace() {
                                chars.next();
                            }
                        }

                        // 消费引号前的空白字符
                        while let Some(&c) = chars.peek() {
                            if c.is_whitespace() {
                                chars.next();
                            } else {
                                break;
                            }
                        }

                        // 解析属性值
                        let mut attr_value = String::new();
                        let quote = chars.next().unwrap_or('"');

                        if quote == '"' || quote == '\'' {
                            // 有引号的情况
                            while let Some(c) = chars.next() {
                                if c == quote {
                                    break;
                                }
                                attr_value.push(c);
                            }
                        } else {
                            // 无引号的情况
                            attr_value.push(quote); // 把之前获取的第一个字符放回去
                            while let Some(&c) = chars.peek() {
                                if c.is_whitespace() || c == '>' || c == '/' {
                                    break;
                                }
                                attr_value.push(chars.next().unwrap());
                            }
                        }

                        // 添加属性
                        element.add_attribute(&attr_name, &attr_value);
                    }

                    // 检查是否是自闭合标签
                    let is_self_closing = chars.peek() == Some(&'/');
                    if is_self_closing {
                        chars.next(); // 消费/
                    }

                    // 消费结束>
                    if chars.peek() == Some(&'>') {
                        chars.next();
                    }

                    // 如果不是自闭合，且不是void元素，递归解析子元素
                    if !is_self_closing && !self.is_void_element(&Cow::Owned(tag_name.clone())) {
                        let remaining = chars.collect::<String>();

                        // 记录当前位置，递归解析子元素
                        self.parse_html_fragment(&remaining, &mut element)?;

                        // 添加元素到父节点
                        parent.children.push(element);

                        // 已经处理完整个字符串
                        break;
                    } else {
                        // 自闭合或void元素直接添加到父节点
                        parent.children.push(element);
                    }
                }
                _ => {
                    // 累积文本内容
                    current_text.push(c);
                }
            }
        }

        // 处理最后累积的文本
        if (!current_text.is_empty()) {
            if (!current_text.trim().is_empty() || self.config.preserve_whitespace) {
                parent.children.push(DomNode::new_text(&current_text));
            }
        }

        Ok(())
    }

    /// 优化HTML文档
    pub fn optimize(&self, node: &mut DomNode) {
        // 修复语法错误 - 移除多余的括号
        if !self.config.preserve_whitespace {
            node.children.retain(|child| {
                if let NodeType::Text(text) = &child.node_type {
                    !text.trim().is_empty()
                } else {
                    true
                }
            });
        }

        // 合并相邻的文本节点
        let mut i = 0;
        while i < node.children.len().saturating_sub(1) {
            if let (NodeType::Text(text1), NodeType::Text(text2)) =
                (&node.children[i].node_type, &node.children[i + 1].node_type)
            {
                let mut new_text = text1.clone();
                new_text.push_str(text2);
                node.children[i].node_type = NodeType::Text(new_text);
                node.children.remove(i + 1);
            } else {
                i += 1;
            }
        }

        // 递归优化子节点
        for child in &mut node.children {
            self.optimize(child);
        }
    }

    /// 序列化DOM树为HTML字符串
    ///
    /// 如果fragment为true，则仅序列化当前节点及其子节点
    /// 如果fragment为false，则添加完整的HTML文档结构
    pub fn to_html(&self, node: &DomNode, pretty: bool) -> String {
        let mut output = String::new();
        self.to_html_inner(node, &mut output, 0, pretty);

        // 确保输出的HTML是有效的UTF-8
        if pretty {
            output = format!("<!DOCTYPE html>\n{}", output);
        }

        output
    }

    // 新增：片段序列化方法 - 无缩进和格式
    fn serialize_fragment(&self, node: &DomNode, output: &mut String) {
        match &node.node_type {
            NodeType::Document => {
                // 对于文档节点，序列化所有子节点
                for child in &node.children {
                    self.serialize_fragment(child, output);
                }
            }
            NodeType::Element(tag_name) => {
                // 开始标签
                output.push('<');
                output.push_str(tag_name.as_ref());

                // 属性
                for attr in &node.attributes {
                    output.push(' ');
                    output.push_str(&attr.name);
                    output.push_str("=\"");
                    output.push_str(&attr.value);
                    output.push('"');
                }

                if self.is_void_element(tag_name) {
                    output.push_str("/>");
                } else {
                    output.push('>');

                    // 子节点
                    for child in &node.children {
                        self.serialize_fragment(child, output);
                    }

                    // 结束标签
                    output.push_str("</");
                    output.push_str(tag_name.as_ref());
                    output.push('>');
                }
            }
            NodeType::Text(text) => {
                output.push_str(text);
            }
            NodeType::Comment(comment) => {
                if self.config.preserve_comments {
                    output.push_str("<!--");
                    output.push_str(comment);
                    output.push_str("-->");
                }
            }
            NodeType::DocumentType(doctype) => {
                output.push_str("<!DOCTYPE ");
                output.push_str(doctype);
                output.push('>');
            }
        }
    }

    // 原有的serialize_node方法保持不变
    fn serialize_node(&self, node: &DomNode, output: &mut String, indent_level: usize) {
        let indent = "    ".repeat(indent_level);

        match &node.node_type {
            NodeType::Document => {
                output.push_str("<!DOCTYPE html>\n");
                for child in &node.children {
                    self.serialize_node(child, output, indent_level);
                }
            }

            NodeType::Element(tag_name) => {
                output.push_str(&indent);
                output.push('<');
                output.push_str(tag_name.as_ref());

                // 优先添加xmlns属性
                if let Some(ns) = &node.namespace {
                    if !node.has_attribute("xmlns") {
                        output.push_str(" xmlns=\"");
                        output.push_str(ns);
                        output.push('"');
                    }
                }

                // 添加其他属性
                for attr in &node.attributes {
                    output.push(' ');
                    output.push_str(&attr.name);
                    output.push_str("=\"");
                    output.push_str(&attr.value);
                    output.push('"');
                }

                // 处理自闭合标签
                if self.is_void_element(tag_name)
                    || (node.is_svg_element() && node.children.is_empty())
                {
                    output.push_str("/>\n");
                } else {
                    output.push('>');
                    output.push('\n');

                    // 递归处理子节点
                    for child in &node.children {
                        self.serialize_node(child, output, indent_level + 1);
                    }

                    output.push_str(&indent);
                    output.push_str("</");
                    output.push_str(tag_name.as_ref());
                    output.push_str(">\n");
                }
            }

            NodeType::Text(text) => {
                if (!text.trim().is_empty() || self.config.preserve_whitespace) {
                    output.push_str(&indent);

                    // 保留HTML实体而不解码它们
                    output.push_str(text);
                    output.push('\n');
                }
            }

            NodeType::Comment(comment) => {
                if self.config.preserve_comments {
                    output.push_str(&indent);
                    output.push_str("<!--");
                    output.push_str(comment);
                    output.push_str("-->\n");
                }
            }

            NodeType::DocumentType(doctype) => {
                output.push_str(&indent);
                output.push_str("<!DOCTYPE ");
                output.push_str(doctype);
                output.push_str(">\n");
            }
        }
    }

    /// 检查是否为自闭合标签
    fn is_void_element(&self, tag_name: &Cow<'static, str>) -> bool {
        static VOID_ELEMENTS: [&str; 14] = [
            "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
            "source", "track", "wbr",
        ];
        VOID_ELEMENTS.contains(&(tag_name.as_ref()))
    }

    /// 使用选择器查找节点
    pub fn query_selector<'a>(
        &self,
        node: &'a DomNode,
        selector_str: &str,
    ) -> Result<Vec<&'a DomNode>, HtmlParserError> {
        let selector = selector_str
            .parse::<Selector>()
            .map_err(|_| HtmlParserError::ParseError("无效的选择器".to_string()))?;

        let mut results = Vec::new();
        {
            let mut collect = |n: &'a DomNode| {
                if selector.matches(n) {
                    results.push(n);
                }
            };
            self.traverse(node, &mut collect);
        }
        Ok(results)
    }

    /// 遍历DOM树
    pub fn traverse<'a>(&self, node: &'a DomNode, callback: &mut dyn FnMut(&'a DomNode)) {
        callback(node);
        for child in &node.children {
            self.traverse(child, callback);
        }
    }

    // 新增方法: 获取检测到的编码名称
    pub fn get_detected_encoding(&self) -> &str {
        self.encoding_detector.get_encoding_name()
    }

    /// 检查语言是否为RTL
    pub fn is_rtl_language(&self, lang_code: &str) -> bool {
        self.i18n.is_rtl_language(lang_code)
    }

    /// 获取元素的文本方向
    pub fn get_element_direction(&self, node: &DomNode) -> TextDirection {
        // 检查dir属性
        if let Some(dir) = node.get_attribute("dir") {
            match dir.to_lowercase().as_str() {
                "rtl" => return TextDirection::RightToLeft,
                "ltr" => return TextDirection::LeftToRight,
                _ => {}
            }
        }

        // 检查lang属性
        if let Some(lang) = node
            .get_attribute("lang")
            .or_else(|| node.get_attribute("xml:lang"))
        {
            return self.i18n.get_text_direction(&lang);
        }

        // 默认从左到右
        TextDirection::LeftToRight
    }

    /// 解码HTML实体
    pub fn decode_html_entities(&self, text: &str) -> String {
        // 使用国际化模块中的方法
        self.i18n.decode_html_entities(text)
    }

    // 新增方法：将文本转换为HTML安全文本
    fn html_escape(&self, text: &str) -> String {
        text.replace("<", "&lt;")
            .replace(">", "&gt;")
            .replace("&", "&amp;")
            .replace("\"", "&quot;")
            .replace("'", "&#39;")
    }

    /// 获取表单信息
    pub fn extract_forms(&self, dom: &DomNode) -> Result<Vec<form::HtmlForm>, HtmlParserError> {
        // 调用form模块中的实现
        form::extract_forms_impl(self, dom)
    }

    // 内部方法：将DOM转为HTML
    fn to_html_inner(
        &self,
        node: &DomNode,
        output: &mut String,
        indent_level: usize,
        pretty: bool,
    ) {
        if pretty {
            self.serialize_node(node, output, indent_level);
        } else {
            self.serialize_fragment(node, output);
        }
    }
}

/// DOM节点结构体
#[derive(Debug, Clone)]
pub struct DomNode {
    pub node_type: NodeType,
    pub attributes: Vec<Attribute>,
    pub children: Vec<DomNode>,
    pub parent: Option<Rc<RefCell<DomNode>>>,
    pub namespace: Option<String>, // 添加命名空间支持
}

/// 节点类型枚举
#[derive(Debug, Clone, PartialEq)]
pub enum NodeType {
    Element(Cow<'static, str>),
    Text(String),
    Comment(String),
    Document,
    DocumentType(String),
}

/// 节点属性结构体
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
    pub name: String,
    pub value: String,
}

// 为DomNode实现一些有用的方法
impl DomNode {
    /// 创建新的元素节点
    pub fn new_element(tag_name: &str) -> Self {
        Self {
            node_type: NodeType::Element(Cow::Owned(tag_name.to_string())),
            attributes: Vec::new(),
            children: Vec::new(),
            parent: None,
            namespace: None, // 默认无命名空间
        }
    }

    /// 创建新的命名空间元素
    pub fn new_element_ns(tag_name: &str, namespace: &str) -> Self {
        Self {
            node_type: NodeType::Element(Cow::Owned(tag_name.to_string())),
            attributes: Vec::new(),
            children: Vec::new(),
            parent: None,
            namespace: Some(namespace.to_string()),
        }
    }

    /// 创建新的文本节点
    pub fn new_text(text: &str) -> Self {
        Self {
            node_type: NodeType::Text(text.to_string()),
            attributes: Vec::new(),
            children: Vec::new(),
            parent: None,
            namespace: None, // 添加缺失的namespace字段
        }
    }

    /// 创建新的注释节点
    pub fn new_comment(text: &str) -> Self {
        Self {
            node_type: NodeType::Comment(text.to_string()),
            attributes: Vec::new(),
            children: Vec::new(),
            parent: None,
            namespace: None, // 添加缺失的namespace字段
        }
    }

    /// 添加属性
    pub fn add_attribute(&mut self, name: &str, value: &str) {
        // 检查属性是否已存在，如果存在则更新值
        if let Some(attr) = self.attributes.iter_mut().find(|attr| attr.name == name) {
            attr.value = value.to_string();
        } else {
            self.attributes.push(Attribute {
                name: name.to_string(),
                value: value.to_string(),
            });
        }
    }

    /// 添加子节点
    pub fn add_child(&mut self, mut child: DomNode) -> &mut Self {
        // 创建父节点引用
        let parent_ref = Rc::new(RefCell::new(self.clone()));
        child.parent = Some(parent_ref);
        self.children.push(child);
        self
    }

    /// 删除子节点
    pub fn remove_child(&mut self, index: usize) -> Option<DomNode> {
        if index < self.children.len() {
            let mut child = self.children.remove(index);
            // 移除父节点引用
            child.parent = None;
            Some(child)
        } else {
            None
        }
    }

    /// 插入子节点到指定位置
    pub fn insert_child(&mut self, index: usize, mut child: DomNode) -> &mut Self {
        if index <= self.children.len() {
            // 创建父节点引用
            let parent_ref = Rc::new(RefCell::new(self.clone()));
            child.parent = Some(parent_ref);
            self.children.insert(index, child);
        }
        self
    }

    /// 获取属性值
    pub fn get_attribute(&self, name: &str) -> Option<&str> {
        self.attributes
            .iter()
            .find(|attr| attr.name == name)
            .map(|attr| attr.value.as_str())
    }

    /// 检查节点是否具有特定属性
    pub fn has_attribute(&self, name: &str) -> bool {
        self.attributes.iter().any(|attr| attr.name == name)
    }

    /// 获取节点的命名空间
    pub fn get_namespace(&self) -> Option<&str> {
        self.namespace.as_deref()
    }

    /// 是否是SVG元素
    pub fn is_svg_element(&self) -> bool {
        if let Some(ns) = &self.namespace {
            return ns == crate::svg::SVG_NAMESPACE;
        }
        false
    }

    /// 是否是MathML元素
    pub fn is_mathml_element(&self) -> bool {
        if let Some(ns) = &self.namespace {
            return ns == crate::mathml::MATHML_NAMESPACE;
        }
        false
    }

    /// 查找单个子节点
    pub fn query_selector(&self, selector_str: &str) -> Option<&DomNode> {
        if let Ok(selector) = selector_str.parse::<Selector>() {
            for child in &self.children {
                if selector.matches(child) {
                    return Some(child);
                }

                // 递归查找 - 继续使用原始选择器字符串
                if let Some(found) = child.query_selector(selector_str) {
                    return Some(found);
                }
            }
        }
        None
    }

    /// 获取文本内容（包括所有子文本节点）
    pub fn text_content(&self) -> String {
        let mut content = String::new();

        match &self.node_type {
            NodeType::Text(text) => {
                content.push_str(text);
            }
            _ => {
                for child in &self.children {
                    content.push_str(&child.text_content());
                }
            }
        }

        content
    }

    /// 检查节点是否包含指定的类名
    pub fn has_class(&self, class_name: &str) -> bool {
        if let Some(class_attr) = self.get_attribute("class") {
            class_attr.split_whitespace().any(|c| c == class_name)
        } else {
            false
        }
    }

    /// 移除一个属性
    pub fn remove_attribute(&mut self, name: &str) -> bool {
        let len = self.attributes.len();
        self.attributes.retain(|attr| attr.name != name);
        len != self.attributes.len()
    }

    /// 获取元素的语言
    pub fn get_language(&self) -> Option<&str> {
        self.get_attribute("lang")
            .or_else(|| self.get_attribute("xml:lang"))
    }

    /// 获取元素的文本方向属性
    pub fn get_direction(&self) -> Option<&str> {
        self.get_attribute("dir")
    }

    /// 检查元素是否有RTL方向
    pub fn is_rtl(&self) -> bool {
        if let Some(dir) = self.get_direction() {
            dir.eq_ignore_ascii_case("rtl")
        } else {
            false
        }
    }
}
